using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Runtime.Serialization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using T.FAS.Runtime.DataAccess.SPI;
using T.FAS.Runtime.DataAccess.Service;
using T.FAS.Runtime.Metadata.Entity.DataModel;
using T.FAS.Runtime.DataModel.Dao;
using T.FAS.Runtime.DataAccess.ShardingRule;
using T.FAS.Runtime.DataAccess.SQLDom;
using T.FAS.Runtime.DataAccess.Common;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.DataModel.Plugin;
using T.FAS.Runtime.DataAccess.Engine;
using System.Threading;
using AppContext = T.ServiceComponent.Session.Service.AppContext;
using Newtonsoft.Json.Linq;
using T.FAS.Runtime.DataModel.Plugin;

namespace T.FAS.Runtime.DataAccess.UnitTest
{
    [TestClass]
    public class CDOEngineTest_PermissionMask
    {
        //public const string cdoID = "1c310fa6-2b13-4f92-8259-a7868171821e";//xer
        public const string cdoID = "3a44fe52-6ad8-484b-bc39-171bd4c50780";//liufei
        //public const string dqID = "15c1f358-4f49-4f98-8675-ab2feb869b1a";  //xer
        public const string dqID = "34b5f785-625e-43f2-a8ed-e8efdf6106f9";  //liufei
        CompositeDataObjectRTPManager _cdoManager = new CompositeDataObjectRTPManager();
        DataQueryRTPManager _dqManager = new DataQueryRTPManager();
        private readonly ChangeSetService _changeService = new ChangeSetService();
        CompositeDataObject cdo;
        DataQuery dq;
        TRecord templateTRecord;
        

        [TestInitialize]
        public void Init()
        {
            LiveDebug.IsDebug = true;
            LiveDebug.IsAllAuth = true;
            //初始化cdo
            cdo = _cdoManager.GetMetaDataContent(cdoID) as CompositeDataObject;
            PackageCDOMetaData(cdo);
            cdo.BuildModelObjectRelation();
            cdo.RootCompositeNodeObject.Associations.ForEach(asso =>
            {
                if (asso.AssociateType == AssociateType.OuterLeftJoin)
                {
                    asso.AssoDataObject = new DataObject();
                }
            });

            dq = _dqManager.GetMetaDataContent(dqID) as DataQuery;
            PackageDQMetaData(dq);

            JObject obj = JObject.Parse(json);
            templateTRecord = TRecord.BuildRecord(obj);
        }

        string json3 = @"{
    ""ID"": ""f48e2205-444d-6431-8aee-a170dae8c14d"",
    ""Code"": ""001"",
    ""Name"": ""掩码测试"",
    ""Mobile"": ""12345678901"",
    ""Mobile_mask"": """",
    ""Email"": ""12345678901@qq.com"",
    ""IDCardNo"": ""370123456789098765"",
    ""IDCardNo_mask"": """",
}";

        string json = $@"{{
	        'ID': '{pk}',
	        'Name': 'xer测试new_5',
	        'Phone': '77777777777',
	        'Phone_mask': null,
	        'EMail': '77777777777',
	        'EMail_mask': '******',
	        'SFCode': '8888888888',
	        'SFCode_mask': null,
	        'Salary': 1000000,
	        'Salary_mask': '******',
	        'bate': '77777777777',
	        'SysNoQuer': '77777777777',
	        'SysNoQuer_mask': '77777777777',
	        'SysNoQuer_mask_mask': '******'
        }}";


        static string pk = "4b8cdb48-a539-2482-bf64-84c9ec587bde";

        [TestMethod]
        public void TestGetMask()
        {
            var context = new Dictionary<string, object>
            {
                {DACConst.ExtSetting,  "{\"isAll\":false,\"columns\":[\"Mobile\", \"IDCardNo\"]}"},
            };
            TRecord tRecord = QueryRecord(context);
            Console.WriteLine(TRecord.ToJson(tRecord));
        }

        private TRecord QueryRecord(Dictionary<string, object> context)
        {
            TResult tResult = UnifiedDataAccessServiceFactory.GetInstance().QueryDataForCDO(cdo, pk, context);
            TRecord tRecord = ((TCommonResult<TRecord>)tResult).Record;
            return tRecord;
        }


        [TestMethod]
        public void TestSaveMask()
        {
            try
            {
                try
                {
                    UnifiedDataAccessServiceFactory.GetInstance().DeleteDataSetForCDO(cdo, new List<string> { pk });
                } 
                catch
                {
                }

                TResult tResult = UnifiedDataAccessServiceFactory.GetInstance().SaveDataForCDO(cdo, templateTRecord);
                var tRecord = ((TCommonResult<TRecord>)tResult).Record;
            }
            catch (Exception e)
            {

                throw;
            }
        }

        [TestMethod]
        public void TestUpdateMask()
        {
            try
            {
                //TestSaveMask();
                var context = new Dictionary<string, object>
                {
                    {DACConst.ExtSetting,  "{\"isAll\":true,\"columns\":[\"Mobile\", \"IDCardNo\"]}"},
                };
                TRecord updateTRecord = QueryRecord(context);
                updateTRecord = TRecord.BuildRecord(JObject.Parse(json));
                //updateTRecord.SetValue("Phone", "77777777777");
                //updateTRecord.SetValue("Phone_mask", "");
                //updateTRecord.SetValue("Email", "11111111111@qq.com");

                //第一次更新，获取变更日志
                var change1 = _changeService.GetChangeSet(cdo, ChangeSetType.Update, updateTRecord);
                TResult tResult = UnifiedDataAccessServiceFactory.GetInstance().UpdateDataForCDO(cdo, updateTRecord);
                var tRecord = ((TCommonResult<TRecord>)tResult).Record;
            }
            catch (Exception e)
            {

                throw;
            }
        }

        [TestMethod]
        public void TestDQQuery()
        {
            //测试用
            LiveDebug.IsDebug = true;
            LiveDebug.IsAllAuth = true;
            var json = @"[
  {
    ""ID"": ""6baa9b70-07bd-41d5-a03e-e91da5a97ceb"",
    ""ColumnName"": ""Phone"",
    ""DisplayName"": ""手机号"",
    ""IsEnableColumnPermission"": true,
    ""MaskingRulesContent"": ""{\""IsEnable\"":true,\""IsPartialMasking\"":false,\""MaskingCharacter\"":\""*\"",\""MaskingType\"":0,\""RuleName\"":\""手机号前后两位掩码\"",\""RegPattern\"":\""^\\\\d{2}(\\\\d{7})\\\\d{2}$\"",\""Replacement\"":\""**$1**\"",\""RuleID\"":\""001\""}"",
    ""DoId"": ""8a3c1e80-ef92-4183-ba3c-d98186384e14"",
    ""DoCode"": ""DO_TestMaskData"",
    ""DoName"": ""测试掩码数据对象"",
    ""LogicTableName"": ""TestMaskData""
  },
  {
    ""ID"": ""8ad93e64-ca91-4c2c-a0a2-0cb52d5c6be7"",
    ""ColumnName"": ""Email"",
    ""DisplayName"": ""邮箱"",
    ""IsEnableColumnPermission"": true,
    ""MaskingRulesContent"": """",
    ""DoId"": ""8a3c1e80-ef92-4183-ba3c-d98186384e14"",
    ""DoCode"": ""DO_TestMaskData"",
    ""DoName"": ""测试掩码数据对象"",
    ""LogicTableName"": ""TestMaskData""
  },
  {
    ""ID"": ""45cd3e17-4884-47bf-9481-3cc7d8660599"",
    ""ColumnName"": ""IDCardNo"",
    ""DisplayName"": ""身份证号"",
    ""IsEnableColumnPermission"": true,
    ""MaskingRulesContent"": ""{\""IsEnable\"":true,\""IsPartialMasking\"":false,\""MaskingCharacter\"":\""*\"",\""MaskingType\"":0,\""RuleName\"":\""身份证号除后四位外掩码\"",\""RegPattern\"":\""^\\\\d{14}(\\\\w{4})$\"",\""Replacement\"":\""**************$1\"",\""RuleID\"":\""002\""}"",
    ""DoId"": ""8a3c1e80-ef92-4183-ba3c-d98186384e14"",
    ""DoCode"": ""DO_TestMaskData"",
    ""DoName"": ""测试掩码数据对象"",
    ""LogicTableName"": ""TestMaskData""
  }
]
";
            var list = JsonConvert.DeserializeObject<List<ColumnPermissionView>>(json);
            string[] strings = new string[] { "IDCardNo", "Email" };
            list.RemoveAll(x => strings.Contains(x.ColumnName));
            AuthTool.ColumnPermissionViews = list;

            Dictionary<string, object> parameters = new Dictionary<string, object> 
            {
                //{DACConst.ExtSetting,"{\"isAll\":false,\"columns\":[\"Mobile\", \"IDCardNo\"]}" }
            };
            var result = UnifiedDataAccessServiceFactory.GetInstance().QueryDataForDataQuery(dq, parameters);
            Console.WriteLine(JsonConvert.SerializeObject(result));
        }


        private void PackageCDOMetaData(CompositeDataObject cdo)
        { 
            DACLocalTestTool.PackagingDependencyMetaData(cdo, true);
        }

        private void PackageDQMetaData(DataQuery dq)
        {
            DACLocalTestTool.InitializeDQ(dq, isGetFromDB: true);
        }
    }
}
